//
//  MTLuckyView.swift
//  MT
//
//  Created by ooops on 2020/1/21.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit

@objc protocol MTLuckyViewDelagate: NSObjectProtocol {
    
    @objc optional func luckViewStart()
    
    @objc optional func luckViewStop()
    
}

class MTLuckyView: UIView {

    weak var delegate: MTLuckyViewDelagate?
    
    private var buttonArray: [MTLuckyItemView] = []
    
    private var stopCount: Int = 0
    
    private var stopTime: TimeInterval = 0
    
    private var time: TimeInterval = 0
    
    private var startTimer: Timer?
    
    private var currentTime: TimeInterval = 0
    
    private var moveTime: TimeInterval = 0
    
    private var countNumber: Int = 0
    /// 中奖结果数组
    private var mutArray: [Int] = []
    
    private var titleArray: [String]?
    
    private var treasureArray: [MTLuckyMoneyModel] = []
    
    /// 循环的上一个按钮
    private var temp: MTLuckyItemView?
    
    var testArray: [Int] = [] {
        didSet {
            self.mutArray.removeAll()
            self.mutArray = testArray
            
            let count = self.mutArray[self.countNumber]
            
            self.currentTime = 0
            self.moveTime = 0.05
            self.time = 0.05
            
            self.stopCount = count
            
            self.stopTime = 8 + Double(treasureArray.count) * 1 + TimeInterval(self.stopCount)
            
            self.startTimer = Timer.scheduledTimer(timeInterval: self.time, target: self, selector: #selector(start(_:)), userInfo: nil, repeats: true)
        }
    }
    
    @objc private func start(_ timer: Timer) {
        self.delegate?.luckViewStart?()
        
        if self.temp != nil {
            self.temp?.hiddenMaskView(isHidden: true)
        }
        
        let oldView: MTLuckyItemView = self.buttonArray[Int(self.currentTime) % self.buttonArray.count]
        
        oldView.hiddenMaskView(isHidden: false)
        
        self.temp = oldView
        
        if self.currentTime > self.stopTime {
            timer.invalidate()
            self.stop(Int(self.currentTime) % self.buttonArray.count)
            return
            
        }
        self.currentTime = self.currentTime + 1
        
        /// 一直循环
        if self.currentTime > self.stopTime - 6 {
            self.time = self.time + 0.05
            timer.invalidate()
            self.startTimer = Timer.scheduledTimer(timeInterval: self.time, target: self, selector: #selector(start(_:)), userInfo: nil, repeats: true)
        }
    }
    
    private func stop(_ count: Int) {
        // over
        if count != 0 {
            let oldView = self.buttonArray[count - 1]
            oldView.hiddenHoverMaskView(isHidden: false)
            
            let lastOldView = self.buttonArray[count]
            lastOldView.hiddenMaskView(isHidden: true)
        } else {
           let oldView = self.buttonArray[8]
            oldView.hiddenHoverMaskView(isHidden: false)
            
            let lastOldView = self.buttonArray[0]
            lastOldView.hiddenMaskView(isHidden: true)
        }
        
        // real over
        
        if self.countNumber < self.mutArray.count - 1 {
            let timeInterval = TimeInterval(1)
            self.countNumber = self.countNumber + 1
            DispatchQueue.main.after(timeInterval) {
                self.again()
            }
        } else {
            Thread.sleep(forTimeInterval: TimeInterval(1))
            self.countNumber = 0
            self.delegate?.luckViewStop?()
            
            for v in self.buttonArray {
                v.hiddenMaskView(isHidden: true)
                v.hiddenHoverMaskView(isHidden: true)
            }
        }
    }
    
    private func again() {
        
        let count = self.mutArray[self.countNumber]
        
        let count2 = self.mutArray[self.countNumber - 1]
        
        self.currentTime = TimeInterval(count2)
        
        self.time = self.moveTime
        
        self.stopCount = count
        
        self.stopTime = 8 + Double(treasureArray.count) * 1 + TimeInterval(self.stopCount)
        
        self.startTimer = Timer.scheduledTimer(timeInterval: self.time, target: self, selector: #selector(start(_:)), userInfo: nil, repeats: true)
        
    }
    
    
    /// 初始化方法
    /// - Parameters:
    ///   - treasureArray: treasureArray - 奖品数组
    convenience init(treasureArray: [MTLuckyMoneyModel]) {
        self.init(frame: .zero)
        
        self.treasureArray = treasureArray
        setupUI()
    }
    
    private func setupUI() {
        for i in 0..<self.treasureArray.count {
            let model: MTLuckyMoneyModel = self.treasureArray[i]
            let luckV = MTLuckyItemView(money: "\(model.ticketAmount ?? 0)", description: "点券")
            addSubview(luckV)
            buttonArray.append(luckV)
        }
        
        // verticalSpacing   每个view之间的垂直距离
        // horizontalSpacing 每个view之间的水平距离
        // warpCount 每行多少列
        // edgeInset 整个布局的 上下左右边距，默认为 .zero
        // itemHeight 每个view的高度， 默认为 nil，可以不指定，那么每个view的高度就按整个容器的高度来确定
        // topConstrainView 整个布局之上的view, 从topConstrainView.snp.bottom开始计算，
        // 比如,传入上面的label,则从 label.snp.bottom + edgeInset.top 开始排列， 默认为nil, 此时布局从 superview.snp.top + edgeInset.top 开始计算
        buttonArray.snp.distributeSudokuViews(verticalSpacing: 10, horizontalSpacing: 10, warpCount: 3, edgeInset: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), itemHeight: 100, topConstrainView: nil)
    }

}
